require([ 'jquery', 'common', 'validate','timepicker', 'pagination', 'bootstrap', 'dateZh','plupload','T_upload'], function($, common,validate,timepicker,T_upload) {
	
	//日期控件
	$('#date-start, #date-end').datetimepicker({
		format : "yyyy-mm-dd hh:ii:ss",
		language : "zh-CN",
		todayBtn : 1,
		autoclose : true,
		todayHighlight : true,
		forceParse : true,
		minuteStep : 10
	});
	
	var addProductBrandForm = $('#addProductBrandForm');
	var updateProductBrandForm = $('#updateProductBrandForm');
	
	var first_load = true;
	var reload = true;
	var getstate = ['','<span style="color:green">上架</span>','<span style="color:red">下架</span>'];
	
	//placeholder兼容ie start
	$(function() {
		if (!placeholderSupport()) { // 判断浏览器是否支持 placeholder
			$('[placeholder]').focus(function() {
				var input = $(this);
				if (input.val() == input.attr('placeholder')) {
					input.val('');
					input.removeClass('placeholder');
				}
			}).blur(function() {
				var input = $(this);
				if (input.val() == ''
						|| input.val() == input.attr('placeholder')) {
					input.addClass('placeholder');
					input.val(input.attr('placeholder'));
				}
			}).blur();
		};
		
		showProductBrandByPage(1);
		$("#updateImgIds").val('');
	});
	function placeholderSupport() {
		return 'placeholder' in document.createElement('input');
	}
	//placeholder兼容ie end

	//清除按钮
	$('.clearBtn').on('click', function() {
		$('.setTableLength').val(10);
		$("#productBrandName").val(''), 
		$("select[name='status']").val('')
	});
	
	$(".setTableLength").change(function() {
		reload = true;
		showProductBrandByPage(1);
	});

	$(".searchBtn").click(function() {
		reload = true;
		showProductBrandByPage(1);
	});
	
	/** 列表查询start **/
	function showProductBrandByPage(pageNum) {
		if ($(".all").is(':checked')) {
			$(".all").removeAttr('checked');								
		}	
		if($('.alert-warning').length>0){
    		$('.alert-warning').remove();
    	}
		$.getJSON(ctx + '/productbrand/showbypage', {	
				pageNum : pageNum,
				pageSize : $('.setTableLength').val() || 10, 
				brandName : $("#productBrandName").val(), 
				status : $("select[name='status']").val()
			},
			function(data){  
				if($('.loading')){
					$('.loading').remove();
				}
				var result = data.result;
				if(result!=null && result=="noauthority") {
					common.alert1('你无此权限!');
					return;
				}
				if(data.result!=null && data.result=="againLogin") {
					common.alert1("登录过期，请重新登录");
						setTimeout("location.href = ctx + '/login.html'",1000);
       			} else if(data.result.length == 0) { 
					$('.table-responsive').append('<div class="alert alert-warning no-result text-center" role="alert">没有找到记录 </div>');
                } else{
       				var datapage = data.result;
					var datalist = datapage.result;
					var totalCount = datapage.totalCount;
					var pageNum = datapage.pageNo;
					var pageSize = datapage.pageSize;
					var totalPages = datapage.totalPages;
					$(".totalCount").html(totalCount);
					$(".totalPages").html(totalPages);
					$(".pageNo").html(pageNum);
                    var tempHtml="";   
                    var ser = 1;
                    for(var i=0;i<datalist.length;i++){   
                    	var productList = datalist[i];
                    	var no = (pageNum-1)*pageSize+i+1; 
                    	tempHtml +="<tr data-id='"+productList.id+"' data-pageno='" + pageNum + "'>";
                    	tempHtml +="<td><div class='checkbox'><label><input type='checkbox' data-roleid="+productList.id+" name='itemCheck' value="+productList.id+" /></label></div></td>";
                    	tempHtml +="<td>"+ser+"</td>"; 
                    	tempHtml +="<td>"+isnull(productList.brandName)+"</td>"; 
                    	tempHtml +="<td>"+isnull(productList.alias)+"</td>";
                    	tempHtml +="<td>"+status(productList.status)+"</td>"; 
                    	tempHtml +="<td>"+common.getSmpFormatDate(productList.createTime)+"</td>"; 
                    	tempHtml +="<td>";
                    		tempHtml +="<button type='button' data-toggle='modal' data-id=" +productList.id+" data-target='.modal-edit' class='btn btn-warning btn-xs updateproduct'>编辑</button>&nbsp";
	                    	if(productList.state == 1){
	                    		tempHtml +="<button type='button' data-id="+productList.id+" data-state=2 class='btn btn-danger btn-xs update-btn'>下架</button>";
	                    	}else if(productList.state == 2){
	                    		tempHtml +="<button type='button' data-id="+productList.id+" data-state=1 class='btn btn-success btn-xs update-btn'>上架</button>";
	                    	}
                    	tempHtml +="</td>";
                    	ser = ser + 1;
                    	tempHtml +="</tr>";
                    	if($('.alert-warning').length>0){
                    		$('.alert-warning').remove();
                    	}
                    }   
                    if(datalist.length === 0&&$('.alert-warning').length<=0) { 
						$('.table-responsive').append('<div class="alert alert-warning no-result text-center" role="alert">没有找到记录 </div>');
	                } 
                    $('#dataBody').html(tempHtml);
                   
                    if (reload) {
                    	reload = false;
                    	first_load = true;
    					var initPagination = function() {
    						$("#Pagination").pagination(totalCount, {
    							num_edge_entries : 1, // 边缘页数
    							num_display_entries : 4, // 主体页数
    							callback: pageselectCallback,
    							prev_text : "«",
    							next_text : "»",
    							items_per_page : pageSize, 
    							link_to : 'javascript:void(0);'
    						});
    					}();
    					/**分页e**/
                    }
				} 
			}).fail(function (err) { 
				if($('.loading')){
					$('.loading').remove();
				}
				common.alert('服务器错误！请刷新页面重试或联系管理员',"确定"); 
            });  
	}
	
	function pageselectCallback(page_index, jq) {
		if (first_load) { //第一次初始化不需要请求
			first_load = false;
			return false;
		}
		pageNum = page_index + 1;
		showProductBrandByPage(pageNum);
	}
	/** 列表查询end **/
	
	/** 添加验证start **/
	$('#addshopForm').validate({
        rules: {
            'productName': {
                required: true 
            },
            'code': {
                required: true 
            },
            'productType': {
                required: true
            },
            'stock': {
                required: true,
                digits: true,
                min:0
            },
            'weight': {
                number: true
            },
            'price': {
                required: true,
                digits: true,
                number: true
            },
	        'mainImg': {
	        	required: true
	        }
        },
        messages: {
        	'name': {
     		    required: "请填写商品名称" 
     		 },
     		'code': {
                required: "请填写商品编号" 
            },
     		'originalprice': {
                required: "请填写商品市场价格",
                number: "请输入有效的数字"
            },
            'stock': {
            	required: "请填写商品库存数量",
            	digits: "请输入有效的整数",
            	min : "不能小于0"
            },
            'weight': {
                number: "请输入有效的数字"
            },
     		'price': {
     		    required: "请填写商品积分价格",
     		    digits: "请输入有效的整数",
     		    number: "请输入有效的数字"
     		 },
     		'mainImg': {
	        	required: "请选择主图"
	        }
        },
        errorClass: "error",
		success: 'valid',
		unhighlight: function(element, errorClass, validClass) { //验证通过
			$(element).tooltip('destroy').removeClass(errorClass);
		}, 
		errorPlacement: function(label, element) {
			$(element).tooltip('destroy'); /*必需*/
			$(element).attr('title', $(label).text()).tooltip('show');
		},
        onclick: true 
    });
	/** 添加验证end **/
	
	
	//添加后台用户角色
	$("#btn_add").click(function(e){
		var isValid = addProductBrandForm.valid();
		var url;
		var queryType = $("#addProductBrandForm").val();
        if (isValid) { 
    		url = ctx + '/productbrand/save'; 
        	 $.post(url, $('#addProductBrandForm').serialize(),function (data) {
         		if(data.result!=null && data.result=="againLogin"){
	         		$('.commonConfirm').modal('hide');
	         		common.alert1("登录过期，请重新登录");
					setTimeout("location.href = ctx + '/login.html'",1000);
            	}else if(data.result=='success'){
            		$('.modal-staff').modal('hide');
	          		$('.mySuccessModal1').modal({show:true,backdrop: 'static', keyboard: false});
	      	        common.mySuccessModal1('添加成功!','如需继续添加，请点击返回继续添加','返回继续添加','前往列表',
  	        		function () {
  	        			$('.mySuccessModal1').modal('hide');  
  	        			$('.modal-add').modal('hide');  
  	        			showProductBrandByPage(1);
  	        		},
  	        		function () {
  	        			$('.modal-staff').modal('show');
  	        		});
	      	        
	      	        $("#addProductBrandForm").find("input[name='brandName']").val('');
	      			$("#addProductBrandForm").find("input[name='alias']").val(''); 
	      			
              	}else if(data.result=='fail'){
              		$(".errorMsg").html(data.message);
              	}else{
              		$(".errorMsg").html("信息提交错误");
              	}
              },"json"); 
        	
        }
	});
	
	/**删除start */
	$(document).on('click', '.delete-btn', function(){
		var varId = $(this).data("id");
		var parentTr = $(this).parents('tr');
        var pageno = parentTr.data('pageno');
		$('.commonConfirm').modal('show');				
		common.commonConfirm("删除", "确定删除", "",
			function() {
            	 $.post(ctx+"/product/deleteproductbyid", {
    				 id:varId
    			 },function (data) {
    				 var result = data.result;
					 if(result!=null && result=="noauthority") {
						 common.alert1('你无此权限!');
						 return;
					 }
    	    		 if(data.result!=null && data.result=="againLogin") {
    	    			 $('.commonConfirm').modal('hide');
    	    			 common.alert1("登录过期，请重新登录");
    					 setTimeout("location.href = ctx + '/login.html'",1000);
    	             }else if(data.result=='success'){ 
    	            	$('.commonConfirm').modal('hide');
    	     	        common.mySuccessModal2(data.message);
    	     	       showProductBrandByPage(pageno);
    	         	}else{
    	         		common.alert1(data.message);
    	         	}
    	         },"json"); 
			}
		);
	});
	/** 删除end **/
	
	/**上下架start */
	$(document).on('click', '.update-btn', function(){
		var varid = $(this).data("id");
        var state = $(this).data('state');
        var parentTr = $(this).parents('tr');
        var pageno = parentTr.data('pageno');
        if(state == 1){
        	var str = "上架";
		}else if(state == 2){
			var str = "下架";
		}else{
			var str = "--";
		}
		$('.commonConfirm').modal('show');
		common.commonConfirm("修改", "确定"+str+"该商品吗？", "",
			function() {
            	 $.post(ctx+"/product/updatestate", {
    				 id:varid,state:state
    			 },function (data) {
    				 var result = data.result;
					 if(result!=null && result=="noauthority") {
						 common.alert1('你无此权限!');
						 return;
					 }
    	    		 if(data.result!=null && data.result=="againLogin") {
    	    			 $('.commonConfirm').modal('hide');
    	    			 common.alert1("登录过期，请重新登录");
    					 setTimeout("location.href = ctx + '/login.html'",1000);
    	             }else if(data.result=='success'){ 
    	            	$('.commonConfirm').modal('hide');
    	     	        common.mySuccessModal2(data.message);
    	     	       showProductBrandByPage(pageno);
    	         	}else{
    	         		common.alert1(data.message);
    	         	}
    	         },"json"); 
			}
		);
	});
	/** 上下架end **/
	
	/**删除多个s*/
	$('#deleteMany').click(function(e) {
		var ids = "";
		var count = 0;
		var checks = document.getElementsByName("itemCheck");
		console.log(checks);
		for(var i=0;i<checks.length;i++){
			if(checks[i].checked){
				count++;
				ids += checks[i].value + ",";
			}
		}
		if(count<1){
			common.alert1("请至少选择一个");
		}else{
			$('.commonConfirm').modal('show');
			common.commonConfirm("删除", "确定删除", "这"+count+"个品牌吗",
				function() {
	            	 $.post(ctx+"/productbrand/deletebyids", {ids:ids},
	            		function (data) {
		            		 var result = data.result;
		     				 if(result!=null && result=="noauthority") {
		     					 common.alert1('你无此权限!');
		     					 return;
		     				 }
	    		    		 if(data.result!=null && data.result=="againLogin") {
	    		    			 $('.commonConfirm').modal('hide');
	    		    			 common.alert1("登录过期，请重新登录");
	    						 setTimeout("location.href = ctx + '/login.html'",1000);
	    		             }else if(data.result=='success'){ 
	    		         		 $(".commonConfirm").modal('hide');
	    		     	         common.mySuccessModal2(data.message);
	    		     	        showProductBrandByPage(1);
	    		         	}else{
	    		         		$(".updateMsg").html(data.message);
	    		         	}
	    		 },"json"); 
			});
		}
	});
	/**删除多个e*/
	
	/** 修改验证start **/
	$('#updateProductForm').validate({
        rules: {
            'name': {
                required: true 
            },
            'code': {
                required: true 
            },
            'originalprice': {
                required: true,
                number: true
            },
            'stock': {
                required: true,
                digits: true,
                min:0
            },
            'weight': {
                number: true
            },
            'price': {
                required: true,
                number: true
            }
        },
        messages: {
        	'name': {
     		    required: "请填写商品名称" 
     		 },
     		'code': {
                required: "请填写商品编号" 
            },
     		'originalprice': {
                required: "请填写商品市场价格",
                number: "请输入有效的数字"
            },
            'stock': {
            	required: "请填写商品库存数量",
            	digits: "请输入有效的整数",
            	min : "不能小于0"
            },
            'weight': {
                number: "请输入有效的数字"
            },
     		'price': {
     		    required: "请填写商品积分价格",
     		    number: "请输入有效的数字"
     		 }
        },
        errorClass: "error",
		success: 'valid',
		unhighlight: function(element, errorClass, validClass) { //验证通过
			$(element).tooltip('destroy').removeClass(errorClass);
		}, 
		errorPlacement: function(label, element) {
			$(element).tooltip('destroy'); /*必需*/
			$(element).attr('title', $(label).text()).tooltip('show');
		},
        onclick: true 
    });
	/** 修改验证end **/
	
$(document).on('click', '.updateproduct', function (e) { 
        var $this = $(this),
        parentTr = $this.parents('tr'),
        id = $this.data('id'),
        pageno = parentTr.data('pageno');
    	$(".updateMsg").html("");
    	$.getJSON(ctx + '/productbrand/querybyid', {
    		id : id
    	}, function(data) {
    		var result = data.result;
			if(result!=null && result=="noauthority") {
				common.alert1('你无此权限!');
				return;
			}
    		if(data==null || data.length <= 0){
    			$(".updateMsg").html("数据异常,请重试");
    		}else{
    			var product = data.productBrand; 
    			$("#updateProductBrandForm").find("input[name='id']").val(product.id);
    			$('#updateProductBrandForm').find("input[name='brandName']").val(product.brandName);
    			$('#updateProductBrandForm').find("input[name='alias']").val(product.alias);
    		}
    	});
    });

/** 修改start **/
$("#btn_update").click(function() {
 	var isValid = updateProductBrandForm.valid();
     if (isValid) { 	
     	 $.post(ctx+"/productbrand/update", $('#updateProductBrandForm').serialize(),function (data) {
     		var result = data.result;
			if(result!=null && result=="noauthority") {
				common.alert1('你无此权限!');
				return;
			}
     		 if(result!=null && result=="againLogin") {
    			 $('.commonConfirm').modal('hide');
    			 common.alert1("登录过期，请重新登录");;
				 setTimeout("location.href = ctx + '/login.html'",1000);
             }else if(result=='success'){ 
          		 $(".modal-edit").modal('hide');
      	         common.mySuccessModal2('修改成功!');
      	       showProductBrandByPage(1);
          	}else{
          		$(".updateMsg").html(data.message);
          	}
          },"json"); 
     }  
});
/** 修改end **/
	
	 
	
	function isnull(value) {
		if (value == null || value == '' || typeof (value) == "undefined")
			return "--";
		else
			return value;
	}

	/*状态，1启用，2禁用*/
	function status(value) {
		if (value == null || value == ''){
			return "未知";
		}else if(value == 1) {
			return "启用";
		}else if(value == 2) {
			return "禁用";
		} 
	}
	
	function isnumber(value) {
		if (value == null || value == '')
			return "0.00";
		else
			return value;
	}
	
});

function removeImg(t) {
	var o=document.getElementById("resultupdate");//获取父节点
	var a=document.getElementById(t);//获取需要删除的子节点
	o.removeChild(a)//从父节点o上面移除子节点a
	var ids = $("#updateImgIds").val() + t+",";
	$("#updateImgIds").val(ids);
} 
/*e*/

